import sys
from antlr4 import StdinStream, CommonTokenStream, InputStream
from CalcLexer import CalcLexer
from CalcParser import CalcParser
from CalcVisitor import CalcVisitor


class ExprCalculateVisitor(CalcVisitor):
    def visitPrintExpr(self, ctx):
        # 函数名enterR的R指的是非终结符r
        val = self.visit(ctx.expr())
        print(val)
        return val


    def visitBrackets(self, ctx):
        return self.visit(ctx.expr())

    def visitAddSub(self, ctx):
        if ctx.op.type == CalcParser.ADD:
            return self.visit(ctx.left) + self.visit(ctx.right)
        else:
            return self.visit(ctx.left) + self.visit(ctx.right)

    def visitMulDiv(self, ctx):
        if ctx.op.type == CalcParser.MUL:
            return self.visit(ctx.left) * self.visit(ctx.right)
        else:
            return self.visit(ctx.left) / self.visit(ctx.right)

    def visitInt(self, ctx):
        return int(ctx.getText())


def main(s:str):
    if s=="":
        return
    code = s.replace('end', "")
    code= code.strip()
    print("code to run:",s)
    s = InputStream(s)
    lexer = CalcLexer(s)
    stream = CommonTokenStream(lexer)

    parser = CalcParser(stream)
    tree = parser.prog()
    calculator = ExprCalculateVisitor()
    val = calculator.visitPrintExpr(tree)
    print("return value", val)
    with open('log.log', "w") as f:
        f.write("%s"%val)
    if val==eval(code):
        sys.exit(0)
    else:
        sys.exit(1)

if __name__ == '__main__':
    print(len(sys.argv))
    if len(sys.argv)>=2:
        f_name = sys.argv[1]
        with open(f_name) as f:
            main(f.read())
    else:
        # main("1+23*(5+1)end")
        main("")
